package com.cdream.basic.algorithm.leetcode.findElement;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author cdream
 * @date 5/22/21
 */
public class Question18 {
    private List<List<Integer>> res = new ArrayList<>();

    public static void main(String[] args) {
        System.out.println(new Question18().fourSum(new int[]{2, 2, 2, 2, 2}, 8));
    }

    public List<List<Integer>> fourSum(int[] nums, int target) {
        if (nums.length < 4) {
            return res;
        }
        Arrays.sort(nums);
        int l = nums.length;
        for (int i = 0; i < nums.length - 3; i++) {
            if (i != 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            if (nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
                return res;
            }
            if (nums[i] + nums[l - 1] + nums[l - 2] + nums[l - 3] < target) {
                continue;
            }
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j != i + 1 && nums[j - 1] == nums[j]) {
                    continue;
                }
                if (nums[j] + nums[j + 1] + nums[j + 2] + nums[i] > target) {
                    break;
                }
                if (nums[j] + nums[l - 1] + nums[l - 2] + nums[i] < target) {
                    continue;
                }
                int left = j + 1;
                int right = l - 1;
                while (left < right) {
                    int sums = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sums == target) {
                        res.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left<right && nums[left] == nums[left + 1]) {
                            left++;
                        }
                        while (left<right && nums[right] == nums[right -1]) {
                            right--;
                        }
                    }
                    if (sums < target) {
                        left++;
                    } else {
                        right--;
                    }
                }

            }

        }
        return res;
    }
}
